﻿Imports System.Runtime.CompilerServices

'#120 LoadableListActivatorが遅い
'MakeGenericTypeは意外と遅いのでキャッシュ
Friend Module TypeExtension

    ''' <summary>
    ''' LoadableList(Of )の型に変換します
    ''' </summary>
    ''' <param name="source"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    <Extension()>
    Public Function ToLoadableListGenericType(source As Type) As Type
        Static cache As New Dictionary(Of Type, Type)

        If cache.ContainsKey(source) = False Then cache.Add(source, source.ToGenericType(GetType(LoadableList(Of ))))
        Return cache(source)
    End Function

    ''' <summary>
    ''' Query(Of )の型に変換します
    ''' </summary>
    ''' <param name="source"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    <Extension()>
    Public Function ToQueryGenericType(source As Type) As Type
        Static cache As New Dictionary(Of Type, Type)

        If cache.ContainsKey(source) = False Then cache.Add(source, source.ToGenericType(GetType(Query(Of ))))
        Return cache(source)
    End Function

    ''' <summary>
    ''' List(Of )の型に変換します
    ''' </summary>
    ''' <param name="source"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    <Extension()>
    Public Function ToListGenericType(source As Type) As Type
        Static cache As New Dictionary(Of Type, Type)

        If cache.ContainsKey(source) = False Then cache.Add(source, source.ToGenericType(GetType(List(Of ))))
        Return cache(source)
    End Function

    ''' <summary>
    ''' ジェネリック型に変換します
    ''' </summary>
    ''' <param name="source"></param>
    ''' <param name="genType"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    <Extension()>
    Private Function ToGenericType(source As Type, genType As Type) As Type
        Return genType.MakeGenericType({source})
    End Function

End Module
